import 'dart:async';

import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_statistics_once.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_statistics_total.dart';
import '../../service/vehicle_connection_service.dart';
import '../../service/global_service.dart';
import '../../service/realtime_data_server/realtime_data_service.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_battery_info.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_error.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_info.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_status.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_settings.dart';

mixin RealtimeInfoMixin {
  // 车辆实时信息订阅
  StreamSubscription? _realTimeInfoSubscription;

  // 车辆实时状态订阅
  StreamSubscription? _realTimeStateSubscription;

  // 车辆实时错误订阅
  StreamSubscription? _realTimeErrorSubscription;

  // 车辆单次统计数据订阅
  StreamSubscription? _statisticsOnceSubscription;

  // 车辆累计统计总数据订阅
  StreamSubscription? _statisticsTotalSubscription;

  // 车辆电池信息订阅
  StreamSubscription? _batteryInfoSubscription;

  // 车辆设置信息订阅
  StreamSubscription? _settingsSubscription;

  // 循环获取车辆实时数据
  Future<bool> realtimeInfoMixinStartLoopToGetVehicleRealTimeData({
    required List<(PollingTimerType, int)> pollingTypes,
    Function(VehicleRealtimeInfo)? realtimeInfoCallback,
    Function(VehicleRealtimeStatus)? realtimeStatusCallback,
    Function(VehicleRealtimeError)? realtimeErrorCallback,
    Function(VehicleStatisticsOnce)? statisticsOnceCallback,
    Function(VehicleStatisticsTotal)? statisticsTotalCallback,
    Function(VehicleBatteryInfo)? batteryInfoCallback,
    Function(VehicleSettings)? settingsCallback,
  }) async {
    // 订阅车辆信息数据
    _realTimeInfoSubscription = GlobalService.to.realtimeInfo.listen((p0) {
      if (realtimeInfoCallback != null) {
        realtimeInfoCallback(p0);
      }
    });

    // 订阅车辆状态数据
    _realTimeStateSubscription = GlobalService.to.realtimeStatus.listen((p0) {
      if (realtimeStatusCallback != null) {
        realtimeStatusCallback(p0);
      }
    });

    // 订阅车辆错误数据
    _realTimeErrorSubscription = GlobalService.to.realtimeError.listen((p0) {
      if (realtimeErrorCallback != null) {
        realtimeErrorCallback(p0);
      }
    });

    // 订阅车辆统计一次数据
    _statisticsOnceSubscription =
        GlobalService.to.realtimeStatisticsOnce.listen((p0) {
      if (statisticsOnceCallback != null) {
        statisticsOnceCallback(p0);
      }
    });

    // 订阅车辆统计总数据
    _statisticsTotalSubscription =
        GlobalService.to.realtimeStatisticsTotal.listen((p0) {
      if (statisticsTotalCallback != null) {
        statisticsTotalCallback(p0);
      }
    });

    // 订阅车辆电池信息数据
    _batteryInfoSubscription = GlobalService.to.realtimeBattery.listen((p0) {
      if (batteryInfoCallback != null) {
        batteryInfoCallback(p0);
      }
    });

    // 订阅车辆设置数据
    _settingsSubscription = GlobalService.to.realtimeSetting.listen((p0) {
      if (settingsCallback != null) {
        settingsCallback(p0);
      }
    });

    if (VechileConnectionService.to.business == null) {
      return Future.value(true);
    }
    return VechileConnectionService.to.business!
        .startLoopToGetVehicleRealTimeData(pollingTypes: pollingTypes);
  }

  // 停止循环获取车辆实时数据
  Future<bool> realtimeInfoMixinStopLoopToGetVehicleRealTimeData() {
    _mixinStopAllListeners();
    if (VechileConnectionService.to.business == null) {
      return Future.value(true);
    }
    // 停止轮询获取车辆实时数据
    return VechileConnectionService.to.business!
        .stopLoopToGetVehicleRealTimeData();
  }

  // 停止轮询车辆实时数据，下发其他指令后，再次开启轮询
  Future<bool> realtimeInfoMixinStopLoopToGetVehicleRealTimeDataThenStart({
    required List<(PollingTimerType, int)> pollingTypes,
    required Future<bool> Function() action,
  }) {
    return realtimeInfoMixinStopLoopToGetVehicleRealTimeData()
        .then((stopSuccess) {
      if (stopSuccess) {
        // 停止轮询成功后，执行其他指令
        return action();
      }
      return Future.value(false);
    }).whenComplete(() {
      // 无论其他指令成功与否，都再次开启轮询获取车辆实时数据
      realtimeInfoMixinStartLoopToGetVehicleRealTimeData(
          pollingTypes: pollingTypes);
    });
  }

  // toNamed跳转
  realtimeInfoMixinNavigatorToNamed(String route,
      {required List<(PollingTimerType, int)> pollingTypes}) {
    realtimeInfoMixinStopLoopToGetVehicleRealTimeData().then((_) {
      Get.toNamed(route)
          ?.then(
            (value) => realtimeInfoMixinStopLoopToGetVehicleRealTimeData().then(
              (value) => realtimeInfoMixinStartLoopToGetVehicleRealTimeData(
                  pollingTypes: pollingTypes),
            ),
          )
          .catchErrorHandler();
    }).catchErrorHandler();
  }

  // 辅助方法：取消所有监听
  void _mixinStopAllListeners() {
    _realTimeInfoSubscription?.cancel();
    _realTimeInfoSubscription = null;
    _realTimeStateSubscription?.cancel();
    _realTimeStateSubscription = null;
    _realTimeErrorSubscription?.cancel();
    _realTimeErrorSubscription = null;
    _statisticsOnceSubscription?.cancel();
    _statisticsOnceSubscription = null;
    _statisticsTotalSubscription?.cancel();
    _statisticsTotalSubscription = null;
    _batteryInfoSubscription?.cancel();
    _batteryInfoSubscription = null;
    _settingsSubscription?.cancel();
    _settingsSubscription = null;
  }
}
